import { Controller, Get, Post, Body, Put, Delete, Param, Req, BadRequestException } from '@nestjs/common';
import { ArticleService } from './article.service';
import { CreateArticleDto, UpdateArticleDto, ArticleResponseDto } from '../../dto/article.dto';
import type { Request } from 'express';
import { User } from '../../entities/user.entity';
import { Article } from '../../entities/article.entity';
import { ApiTags, ApiOperation, ApiResponse, ApiBody, ApiParam } from '@nestjs/swagger';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserService } from '../user/user.service';

@ApiTags('文章管理')
@Controller('api/articles/user')
export class ArticleUserController {
  constructor(
    private readonly articleService: ArticleService,
    @InjectRepository(Article)
    private readonly articlesRepository: Repository<Article>,
    private readonly userService: UserService
  ) {}

  @Get('my')
  @ApiOperation({
    summary: '获取当前用户的文章列表',
    description: '获取当前登录用户的所有文章',
  })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: [ArticleResponseDto],
  })
  @ApiResponse({
    status: 400,
    description: '用户未登录',
  })
  async findMyArticles(@Req() req: Request): Promise<ArticleResponseDto[]> {
    const user = (req as any).user as User;
    if (!user) {
      throw new BadRequestException('用户未登录');
    }
    // 直接查询用户的所有文章
    const articles = await this.articlesRepository.find({
      where: { authorId: user.id },
      relations: ['tags'],
      order: { createdAt: 'DESC' }
    });
    
    // 转换为响应DTO
    return await Promise.all(
      articles.map(async article => {
        const userData = await this.userService.findOne(article.authorId);
        return new ArticleResponseDto(article, userData);
      })
    );
  }

  @Get(':id')
  @ApiOperation({
    summary: '获取文章详情（用户）',
    description: '登录用户可以获取自己的所有文章，包括未审核的，以及他人审核通过的文章',
  })
  @ApiParam({
    name: 'id',
    description: '文章ID',
    example: '1',
  })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: ArticleResponseDto,
  })
  @ApiResponse({
    status: 404,
    description: '文章不存在或无权访问',
  })
  findOneUser(@Param('id') id: string, @Req() req: Request): Promise<ArticleResponseDto> {
    const user = (req as any).user as User;
    return this.articleService.findOne(+id, user?.id, false);
  }

  @Post()
  @ApiOperation({
    summary: '创建文章',
    description: '创建新的文章',
  })
  @ApiBody({
    type: CreateArticleDto,
    description: '文章信息',
  })
  @ApiResponse({
    status: 201,
    description: '创建成功',
    type: ArticleResponseDto,
  })
  @ApiResponse({
    status: 400,
    description: '参数错误或用户未登录',
  })
  create(@Body() createArticleDto: CreateArticleDto, @Req() req: Request) {
    const user = (req as any).user as User;
    if (!user) {
      throw new BadRequestException('用户未登录');
    }
    return this.articleService.create(createArticleDto, user.id);
  }

  @Put(':id')
  @ApiOperation({
    summary: '更新文章',
    description: '更新指定文章的信息',
  })
  @ApiParam({
    name: 'id',
    description: '文章ID',
    example: '1',
  })
  @ApiBody({
    type: UpdateArticleDto,
    description: '更新的文章信息',
  })
  @ApiResponse({
    status: 200,
    description: '更新成功',
    type: ArticleResponseDto,
  })
  @ApiResponse({
    status: 400,
    description: '参数错误或用户未登录',
  })
  @ApiResponse({
    status: 404,
    description: '文章不存在',
  })
  update(
    @Param('id') id: string,
    @Body() updateArticleDto: UpdateArticleDto,
    @Req() req: Request,
  ) {
    const user = (req as any).user as User;
    if (!user) {
      throw new BadRequestException('用户未登录');
    }
    return this.articleService.update(+id, updateArticleDto, user.id);
  }

  @Delete(':id')
  @ApiOperation({
    summary: '删除文章',
    description: '删除指定的文章',
  })
  @ApiParam({
    name: 'id',
    description: '文章ID',
    example: '1',
  })
  @ApiResponse({
    status: 200,
    description: '删除成功',
  })
  @ApiResponse({
    status: 400,
    description: '用户未登录',
  })
  @ApiResponse({
    status: 404,
    description: '文章不存在',
  })
  remove(@Param('id') id: string, @Req() req: Request) {
    const user = (req as any).user as User;
    if (!user) {
      throw new BadRequestException('用户未登录');
    }
    return this.articleService.remove(+id, user.id);
  }
}